package services;

import java.util.Collection;
import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.OwnershipHistoryRepository;
import domain.OwnershipHistory;
import domain.Painting;

@Service
@Transactional
public class OwnershipHistoryService {

	//Managed Repository
		@Autowired
		private OwnershipHistoryRepository ownershipHistoryRepository;
		
		//Supporting Services
		@Autowired
		private CustomerService customerService;
		
		//Constructor Method
		public OwnershipHistoryService(){
			super();
		}
		//Simple Crud Methods
		
		public OwnershipHistory create(Painting p){
			OwnershipHistory result;
			Date currentMoment;
			
			currentMoment = new Date();
			result = new OwnershipHistory();
			
			result.setActualOwner(true);
			result.setCustomer(customerService.findByPrincipal());
			result.setPainting(p);
			result.setBuyDate(currentMoment);
			result.setSellDate(null);
			
			return result;
		}
		
		public void save(OwnershipHistory oh){
			Assert.notNull(oh);
			
			ownershipHistoryRepository.save(oh);
		}
		
		public OwnershipHistory findOne(int ownershipHistoryId){
			OwnershipHistory result;
			
			result = ownershipHistoryRepository.findOne(ownershipHistoryId);
			
			return result;
		}
		
		public Collection<OwnershipHistory> findAll(){
			Collection<OwnershipHistory> result;
			
			result = ownershipHistoryRepository.findAll();
			
			return result;
		}
		
		//Other Business Methods
		
		public Collection<OwnershipHistory> findByPainting(Painting p){
			Assert.notNull(p);
			
			Collection<OwnershipHistory> result;
			
			result = ownershipHistoryRepository.findByPainting(p.getId());
			
			return result;
		}
		
		public OwnershipHistory findActualOwnershipByPainting(Painting painting){
			Assert.notNull(painting);
			
			OwnershipHistory res;
			
			res = ownershipHistoryRepository.findActualOwnership(painting.getId());
			
			return res;
			
		}
}
